<template>
	<view class="content">
		<scroll-view scroll-y="true" :scroll-into-view="scrollToView" :scroll-top="scrollTop" refresher-threshold="100"
			id="chat-scroll" refresher-enabled="true" :scroll-with-animation="true" :refresher-triggered="triggered"
			refresher-background="lightgreen" @refresherrefresh="onRefresh" :style="{height:paddingBottom}"
			class="scrollBox">

			<view class="chat-item" v-for="(item,index) in msglist" :id="item.id" :key="index">

				<!-- 时间 -->
				<view class="timeBox" v-if="item.isShowTime">
					<text>
						{{getDiffTime(item.gmtCreate)}}
					</text>
				</view>
				<!-- 用户 -->
				<view class="content-wrapper-right" v-if="item.type == 1">
					<u-loading-icon size="20" mode="semicircle" :show="item.isLoading"></u-loading-icon>
					<view class="chat-content-right">{{item.messageList[0].message}}</view>
					<!-- 头像 -->
					<image src="../../static/mine/user.png" class="avator avator-right"></image>
				</view>
				<!-- 机器人 -->
				<view class="content-wrapper-left" v-if="item.type == 2">
					<!-- 头像 -->
					<image src="../../static/mine/robot.png" class="avator avator-left"></image>

					<view class="chat-content-left" v-for="(it,idx) in item.messageList" :key="idx">
						
						<view @click="onParseItemClick(it)">
							
							<u-parse :content="it.message" @imgTap="onImgTap" previewImg :lazyLoad="true"></u-parse>
						</view>
						<view class="feedbackBtnBox" v-if="it.isFeedbackBtnShow">
							<view>以上答案是否对您有帮助?</view>
							<view>
								<view @click="onFeedbackButtonClick(1,it)">
									<u-icon name="thumb-up" color="#2979ff" size="18"></u-icon>
									<text>有帮助</text>
								</view>
								<view @click="onFeedbackButtonClick(0,it)">
									<u-icon name="thumb-down" color="#2979ff" size="18"></u-icon>
									<text>没帮助</text>
								</view>
							</view>

						</view>
						<!-- 图片内容 -->
						<!-- <view v-if="it.type == 2" >
							<u-image :showLoading="true" :src="it.message" width="160px" mode='aspectFill'
								@click="onChatImgClick(it.message)">
						
							</u-image>
						</view> -->
						<!-- 文字内容 -->
						<!-- <view v-else >{{it.message}}</view> -->

					</view>

				</view>

			</view>


		</scroll-view>
		<view class="inputBox">
			<view>
				<u-textarea disableDefaultPadding class="textInput" height="21" :showConfirmBar="false" cursorSpacing="20"
					placeholder="请输入要发送的信息" maxlength='-1' @confirm="onSendMsgBtnClick" v-model="inputtxt"></u-textarea>
			</view>
			<view>
				<u-button :disabled="!inputtxt" class="bt1" text="发送" type="primary"
					@click="onSendMsgBtnClick"></u-button>
			</view>
		</view>
	</view>


</template>

<script>
	import {
		getDiffTime,
		base64ToPath
	} from "@/utils/util.js"

	import {
		queryChatMessagesPage,
		getReply,
		updateUsefulFlag
	} from "@/apis/smartChat.js"

	export default {
		data() {
			return {
				getDiffTime,
				inputtxt: "", //用户输入框中输入的内容
				triggered: false,
				msglist: [{
					id: 'time' + new Date().getTime(),
					messageList: [{
						type: '1', // 1文字 2图片
						message: '您好，我是智能客服小U，很荣幸为您服务，请问有什么可以帮到您的？',
					}],
					userId: '',
					type: '2', //1 用户 2机器人
					isShowTime: true,
					gmtCreate: new Date().getTime()
				}], //用于存放对话内容的列表
				page: 1,
				size: 10,
				scrollToView: '',
				paddingBottom: 'calc(100vh - 80px)',
				newId: '', // 分页需要的上一条数据id
				firstTimeType: 1, // 是否第一次未复 1- 0-否
				scrollTop: '',
				allHeight: 0,
			};
		},
		watch: {
			// msglist:{
			// 	handler(val){
			// 		for (let i in val) {
			// 			if (val[i + 1] && val[i + 1].gmtCreate) {
			// 				if (new Date(val[i].gmtCreate).getTime()
			// 				- new Date(val[i + 1].gmtCreate)
			// 					.getTime() > 1000 * 60 * 5) {
			// 					val[i+1].isShowTime = true
			// 				}
			// 			}
			// 		}
			// 		console.log(val)

			// 	},
			// 	immediate:true,
			// 	deep:true
			// }
		},
		onLoad(option) {},
		methods: {
			onFeedbackButtonClick(val, item) {
				const params = {
					usefulFlag: val,
					id: item.answerId
				}
				updateUsefulFlag(params).then(res => {
					if (res.code == '00000000') {
						item.isFeedbackBtnShow = false
						const msg = {
							id: 'time' + new Date().getTime(),
							messageList: [{
								type: '1', // 1文字 2图片
								message: res.data.message,
								id: res.data.id,
							}],
							userId: res.data.userId,
							type: '2', //1 用户 2机器人
							gmtCreate: res.data.gmtCreate || new Date().getTime()
						}
						this.msglist.push(msg)
						this.$nextTick(() => {
							this.scrollToView = this.msglist[this.msglist.length - 1].id;
						});
					}
				})
			},
			onParseItemClick(val){
				console.log(val)
			},
			onImgTap(res) {
				console.log(res)
			},
			onChatImgClick(imgSrc) {
				// console.log(imgSrc)
				// 预览图片
				uni.previewImage({
					urls: [imgSrc],
					current: 0 //点击图片传过来的下标
				})
			},
			onRefresh() {
				if (this.triggered) return;
				this.triggered = true
				const params = {
					pageSize: this.size,
					pageNumber: this.page,
					id: this.newId
				}
				queryChatMessagesPage(params).then(res => {
					if (res.code == '00000000') {
						this.triggered = false;
						if (res.data && res.data.length) {
							this.newId = res.data[res.data.length - 1].id
							for (let i in res.data) {
								console.log(res.data[i])
								if (res.data[i + 1] && res.data[i + 1].gmtCreate) {
									if (new Date(res.data[i].gmtCreate).getTime() -
										new Date(res.data[i + 1].gmtCreate)
										.getTime() > 1000 * 60 * 5) {
										res.data[i].isShowTime = true
									}
								}
								this.msglist.unshift(res.data[i])
							}
							this.msglist[0].isShowTime = true
						}


					}
				})

			},

			onSendMsgBtnClick() { //定义一个click函数来实现存入对话及api请求
				this.inputtxt = uni.$u.trim(this.inputtxt)
				if (!this.inputtxt) {
					uni.showToast({
						title: '不能发送空白内容',
						icon: 'none',
						duration: 2000
					})
					return
				}
				const msgVal = this.inputtxt
				this.inputtxt = ''
				this.msglist.push({
					id: 'time' + new Date().getTime(),
					isLoading: true,
					messageList: [{
						type: '1', // 1文字 2图片
						message: msgVal,
					}],
					userId: '123131',
					type: '1', //1 用户 2机器人
					pageSize: '10',
					gmtCreate: new Date().getTime()
				}) //将输入框中内容传入存放对话的列表
				this.$nextTick(() => {
					this.scrollToView = this.msglist[this.msglist.length - 1].id;
				});

				const params = {
					question: msgVal,
					noResponseFirstTime: this.firstTimeType,
					questionId:'',
					infoSource:'01' , // 01 正常回答 02 点击问题
				}
				getReply(params).then(res => {
					if (res.code == '00000000') {
						let feedbackType = false // 判断展示有无帮助按钮
						if (res.data.message == '请详细的描述问题，以便小U为您更准确的回答。' || res.data.message ==
							'您的问题小U暂时无法回答，已记录并反馈您的问题，后续会尽快优化哦。') {
							feedbackType = false
							this.firstTimeType = 0
						} else {
							feedbackType = true
							this.firstTimeType = 1
						}
						if (!this.newId) { // 存第一次的id 查历史用
							this.newId = res.data.id
						}
						this.msglist[this.msglist.length - 1].isLoading = false
						if (res.data.gmtCreate) {
							this.msglist[this.msglist.length - 1].gmtCreate = res.data.gmtCreate
						}
						if (this.msglist.length >= 2) {
							let times = new Date().getTime() - new Date(this.msglist[this.msglist.length - 2]
								.gmtCreate).getTime()
							if (times >= 1000 * 60 * 5) { // 间隔大于5min显示时间
								this.msglist[this.msglist.length - 1].isShowTime = true
							}
						} else {
							// this.msglist[this.msglist.length - 1].isShowTime = true
						}
						const msg = {
							id: 'time' + new Date().getTime(),
							messageList: [{
								type: '1', // 1文字 2图片
								message: res.data.message,
								id: res.data.id,
								answerId: res.data.answerId,
								isFeedbackBtnShow: feedbackType
							}],
							userId: res.data.userId,
							type: '2', //1 用户 2机器人
							gmtCreate: res.data.gmtCreate || new Date().getTime()
						}
						this.msglist.push(msg)

						this.$nextTick(() => {
							setTimeout(() => {
								// 累加每个聊天的高度计算回复滚动的高度
								let viewBox = uni.createSelectorQuery().in(this).selectAll(
									".chat-item");
								viewBox.fields({
									size: true
								}, chatArr => {
									let allHeight = this.allHeight
									for (let [idx, i] of chatArr.entries()) {
										// 计算出历史数据的总共高度,除了最后一条数据
										allHeight += i.height
										if (idx == chatArr.length - 1) {
											break
										}
									}
									console.log(chatArr, chatArr[chatArr.length - 1]
										.height)
									if (chatArr[chatArr.length - 1].height > 500) {
										allHeight += 260
										this.allHeight += (chatArr[chatArr.length - 1]
											.height - 260)
									} else {
										allHeight += chatArr[chatArr.length - 1].height
									}

									this.scrollTop = allHeight
								}).exec();
							}, 200)

						});
						// view.fields({
						// 	size: true,
						// 	scrollOffset: true
						// }, data => {
						// 	this.$nextTick(() => {
						// 		console.log(data)
						// 		this.scrollTop = data.scrollTop + 250
						// 		console.log(this.scrollTop)
						// 	});
						// }).exec();


					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.inputBox {
		padding: 10rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		justify-content: space-around;

		&>view:first-child {
			width: 82%;
		}
	}

	.scrollBox {
		padding: 12rpx 10rpx;
		box-sizing: border-box;
		background-color: #f5f5f5;
	}

	.chat-item {

		// margin: 15rpx 0;
		.avator {
			width: 80rpx;
			height: 80rpx;
		}
	}

	.content-wrapper-left,
	.content-wrapper-right {
		display: flex;
		margin-bottom: 20rpx;

	}

	.content-wrapper-right {
		justify-content: flex-end;
	}

	.chat-content-left,
	.chat-content-right {
		padding: 20rpx;
		margin-left: 20rpx;
		box-sizing: border-box;
		max-width: calc(100vw - 200rpx);
		border-radius: 16rpx;
		position: relative;
		word-break: break-all;
	}

	.chat-content-left {

		background-color: #fff;

		margin-left: 20rpx;

		/deep/ ._root {
			overflow: hidden !important;
		}

	}

	.chat-content-left::after {
		position: absolute;
		left: -10rpx;
		top: 30rpx;
		content: '';
		width: 20rpx;
		height: 20rpx;
		background: #fff;
		transform: rotate(45deg);

	}

	.chat-content-right::after {
		position: absolute;
		right: -10rpx;
		top: 30rpx;
		content: '';
		width: 20rpx;
		height: 20rpx;
		background: #66b1ff;
		transform: rotate(45deg);
	}

	.chat-content-right {
		background-color: #66b1ff;
		margin-right: 20rpx;
		color: #fff;
	}

	.timeBox {
		text-align: center;

		text {
			margin: 10rpx auto;
			display: inline-block;
			background-color: #dadada;
			color: #fff;
			padding: 6rpx;
			border-radius: 6rpx;
			font-size: 20rpx;
		}


	}

	.feedbackBtnBox {
		margin-top: 10px;
		font-size: 14px;

		&>view:nth-child(2) {
			display: flex;

			&>view {
				margin-right: 40px;
				display: flex;
			}
		}
	}

</style>